﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using Worktool.CODE_Chris.SQL_DATA;

namespace Worktool
{
    public partial class Login : Form
    {
        private String[,] userData;
        private string password; // User Eingabepassword
        private string dbPassword; // Password from DB
        public Loading loadscreen = new Loading();
        public static Dictionary<string, string> dictSettings = new Dictionary<string, string>();

        public static String connection = "", connectionMASTER = "";
        public static String user = "";
        //public static String db = "192.168.0.57";
        public static String labelPrinterName = "Brother QL-570 LE";
        public static String currentDBName = "Quantum";
        private SQL sql;

        private Boolean isInit = true;

        public static String setFilterCharacters(String str)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (char c in str)
            {
                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
                    (c >= 'a' && c <= 'z') || c == '.' || c == '_')
                {
                    stringBuilder.Append(c);
                }
                else
                {
                    if (c.ToString() == "'") stringBuilder.Append("''"); else stringBuilder.Append("[" + c + "]");
                }
            }
            return stringBuilder.ToString();
        }

        public Login()
        {
            InitializeComponent();
            this.Text = "Login: " + Login.currentDBName; 
            label3.Text = Login.currentDBName;

            init();
        }

        private void init()
        {
            sql = new SQL();
            userData = sql.receiveSQL("SELECT COUNT(*) AS Amount FROM tbl_user", "SELECT ID, name, password, changePW, modSerials, modComm, modIp, modRacks, modRooms, modStammdaten, modDmx, modProv, modMatDetail, modBaufortschritt, modDelivery, modLieferkette FROM tbl_user ORDER BY name");

            //User Combobox füllen
            fillComboBox(comboBox1, userData);

            disableAllModules();

            isInit = false;
        }

        #region Init
        private void disableAllModules()
        {
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            button6.Enabled = false;
            button7.Enabled = false;
            button8.Enabled = false;
            button9.Enabled = false;
            button10.Enabled = false;
            button11.Enabled = false;
            button12.Enabled = false;

            button1.BackColor = Color.Gray;
            button2.BackColor = Color.Gray;
            button3.BackColor = Color.Gray;
            button4.BackColor = Color.Gray;
            button5.BackColor = Color.Gray;
            button6.BackColor = Color.Gray;
            button7.BackColor = Color.Gray;
            button8.BackColor = Color.Gray;
            button9.BackColor = Color.Gray;
            button10.BackColor = Color.Gray;
            button11.BackColor = Color.Gray;
            button12.BackColor = Color.Gray;
        }

        private void fillComboBox(ComboBox box, String[,] data)
        {
            try
            {
                box.DropDownStyle = ComboBoxStyle.DropDownList;
                box.Items.Clear();
                box.DropDownWidth = 300;
                box.DropDownHeight = 500;
                for (int a = 0; a < data.GetLength(1); a++)
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Value = data[0, a];
                    item.Text = data[1, a];
                    box.Items.Add(item);
                }

                box.Text = data[1, 0];
                box.Refresh();

                if(Convert.ToBoolean(data[3,0]))
                {
                    label2.Text = "Please insert a new password";
                    label2.ForeColor = Color.Red;
                }
                else
                {
                    label2.Text = "Enter password";
                    label2.ForeColor = Color.Black;
                }
            }
            catch (Exception e)
            {
                sql.log("FEHLER", e, this.ToString() + ":" + System.Reflection.MethodBase.GetCurrentMethod().Name);
            }
        }

        public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

        public void Login_Load(object sender, EventArgs e)
        {
            loadscreen.Hide();
        }
        #endregion

        #region CheckPassword
        public void pwTest()
        {
            bool change;
            password = textBox1.Text;
            String id = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();
            change = Convert.ToBoolean(getUserValue(id,3));

            if ((change == true) && (textBox1.Text != ""))
            {
                sql.sendSQL("UPDATE tbl_user SET password = '" + CalculateMD5Hash(password) + "', changePW = 0 WHERE ID = " + id);
                setUserValue(id, 2, CalculateMD5Hash(password));
                setUserValue(id, 3, "0");

                Login.user = comboBox1.Text;
                Properties.Settings.Default.Save();
                startUI();
            }
            else
            {
                dbPassword = getUserValue(id, 2);
                if (dbPassword == CalculateMD5Hash(password))
                {
                    Login.user = comboBox1.Text;
                    Properties.Settings.Default.Save();
                    startUI();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Falsches Passwort. Bitte versuchen Sie es noch einmal");
                }
            }
        }

        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
        #endregion

        #region Get/Set Uservalues
        private String getUserValue(String id, int column)
        {
            String returnValue = null;
            for (int a = 0; a < userData.GetLength(1); a++)
            {
                if (userData[0, a] == id)
                {
                    returnValue = userData[column, a];
                    break;
                }
            }
            return returnValue;
        }

        private void setUserValue(String id, int column, String value)
        {
            for (int a = 0; a < userData.GetLength(1); a++)
            {
                if (userData[0, a] == id)
                {
                    userData[column, a] = value;
                    break;
                }
            }
        }
        #endregion

        #region EventHandler
        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                pwTest();
                comboBox1.Focus();
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter && textBox1.Text != "")
            {
                pwTest();
                comboBox1.Focus();
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isInit)
            {
                String id = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();
                textBox1.Text = "";

                try
                {
                    if (Convert.ToBoolean(getUserValue(id, 3)))
                    {
                        label2.Text = "Please insert a new password";
                        label2.ForeColor = Color.Red;
                    }
                    else
                    {
                        label2.Text = "Enter password";
                        label2.ForeColor = Color.Black;
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }

        //
        // Modul Seriennummern öffnen
        //
        private void button1_Click(object sender, EventArgs e)
        {
            Serials serials = new Serials();
            serials.Show();
        }

        //
        // Modul Commissioning öffnen
        //
        private void button2_Click(object sender, EventArgs e)
        {
            Commissioning comm = new Commissioning();
            comm.Show();
        }

        //
        // Modul IpDevices öffnen
        //
        private void button3_Click(object sender, EventArgs e)
        {
            IpDevices ipDevices = new IpDevices();
            ipDevices.Show();
        }

        //
        // Modul Stammdaten öffnen
        //
        private void button4_Click(object sender, EventArgs e)
        {
            Stammdaten stamm = new Stammdaten();
            stamm.Show();
        }

        //
        // Modul DMX öffnen
        //
        private void button5_Click(object sender, EventArgs e)
        {
            DmxDevices dmxDevices = new DmxDevices();
            dmxDevices.Show();
        }

        //
        // Modul Material Detail öffnen
        //
        private void button6_Click(object sender, EventArgs e)
        {
            MaterialDetail matDetail = new MaterialDetail();
            matDetail.Show();
        }

        //
        // Modul Rackcontent Report öffnen
        //
        private void button7_Click(object sender, EventArgs e)
        {
            ReportRacks ReportRacks = new ReportRacks();
            ReportRacks.Show();
        }

        //
        // Modul Roomcontent Report öffnen
        //
        private void button8_Click(object sender, EventArgs e)
        {
            ReportRooms ReportRooms = new ReportRooms();
            ReportRooms.Show();
        }

        //
        // Modul Liefertermine öffnen
        //
        private void button9_Click(object sender, EventArgs e)
        {
            ReportLiefertmine liefertermine = new ReportLiefertmine();
            liefertermine.Show();
        }

        //
        // Modul Bereitstellungstermine öffnen
        //
        private void button10_Click(object sender, EventArgs e)
        {
            ReportBedarfstermine bedarf = new ReportBedarfstermine();
            bedarf.Show();
        }

        //
        // Modul Baufortschritt öffnen
        //
        private void button11_Click(object sender, EventArgs e)
        {
            Baufortschritt bf = new Baufortschritt();
            bf.Show();
        }

        //
        // Modul Lieferkette öffnen
        //
        private void button12_Click(object sender, EventArgs e)
        {
            DeliveryChain dc = new DeliveryChain();
            dc.Show();
        }

        private void button13_Click(object sender, EventArgs e)
        {
            Worktool.CODE_Chris.Version.Version version = new Worktool.CODE_Chris.Version.Version();
            version.ShowDialog();
            version.Dispose();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            sql.setConnectionString(connectionMASTER);

            String[,] version = sql.receiveSQL("SELECT * FROM WORKTOOL_Versions");
            int error = 0;

            for (int a = 0; a < version.GetLength(1); a++)
            {
                if (version[1, a] == System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString())
                {
                    error++;
                    break;
                }
            }

            if (error == 0)
            {
                if (MessageBox.Show("Really ship new Version?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    sql.sendSQL("INSERT INTO WORKTOOL_Versions VALUES('" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + "','" + sql.retrieveLinkerTimestamp().ToString() + "')");
                    MessageBox.Show("Successfully registered new version.", "Info");
                }
            }
            else
            {
                MessageBox.Show("Version already shipped! Process aborted.", "Error");
            }

            sql.setConnectionString(connection);
        }
        #endregion

        #region StartUI
        public void startUI()
        {
            String id = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();

            if (Convert.ToBoolean(getUserValue(id, 4)) == true)
            {
                button1.BackColor = Color.DarkSeaGreen;
                button1.Enabled = true; // Serials
            }
            if (Convert.ToBoolean(getUserValue(id, 5)) == true)
            {
                button2.BackColor = Color.DarkSeaGreen;
                button2.Enabled = true; // Commissioning
            }
            if (Convert.ToBoolean(getUserValue(id, 6)) == true)
            {
                button3.BackColor = Color.SteelBlue;
                button3.Enabled = true; 
            }
            if (Convert.ToBoolean(getUserValue(id, 7)) == true)
            {
                button7.BackColor = Color.BurlyWood;
                button7.Enabled = true; 
            }
            if (Convert.ToBoolean(getUserValue(id, 8)) == true)
            {
                button8.BackColor = Color.BurlyWood;
                button8.Enabled = true; 
            }
            if (Convert.ToBoolean(getUserValue(id, 9)) == true)
            {
                button4.BackColor = Color.SteelBlue;
                button4.Enabled = true; 
            }
            if (Convert.ToBoolean(getUserValue(id, 10)) == true)
            {
                button5.BackColor = Color.SteelBlue;
                button5.Enabled = true; 
            }
            if (Convert.ToBoolean(getUserValue(id, 11)) == true)
            {
                button10.BackColor = Color.BurlyWood;
                button10.Enabled = true;
            }
            if (Convert.ToBoolean(getUserValue(id, 12)) == true)
            {
                button6.BackColor = Color.SteelBlue;
                button6.Enabled = true;
            }
            if (Convert.ToBoolean(getUserValue(id, 13)) == true)
            {
                button11.BackColor = Color.Plum;
                button11.Enabled = true; 
            }
            if (Convert.ToBoolean(getUserValue(id, 14)) == true)
            {
                button9.BackColor = Color.BurlyWood;
                button9.Enabled = true;
            }
            if (Convert.ToBoolean(getUserValue(id, 15)) == true)
            {
                button12.BackColor = Color.DarkSeaGreen;
                button12.Enabled = true; 
            }

            if (user == "Nowottny, Christopher") button14.Enabled = true;
        }
        #endregion

    }
}
